package com.itcast.demoone

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CoroutineScopeActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_coroutine_scope)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 1. 手动创建一个协程作用域
       /* CoroutineScope(Dispatchers.Main).launch {
            Log.d("CoroutinesActivity", "协程开始执行 [线程: ${Thread.currentThread().name}]")

            // 1.1 耗时任务 或者 异步任务
            delay(2000)  // 模拟耗时任务
            Log.d("CoroutinesActivity", "协程结束执行 [线程: ${Thread.currentThread().name}]")
        }

        Log.d("CoroutinesActivity", "主线程继续执行 [线程: ${Thread.currentThread().name}]")*/


        // 2. 线程切换

        Log.d("CoroutinesActivity", "111111 [线程: ${Thread.currentThread().name}]")

        CoroutineScope(Dispatchers.Main).launch {
            Log.d("CoroutinesActivity", "UI操作 [线程: ${Thread.currentThread().name}]")

            // 1.1 耗时任务 或者 异步任务 ---> 切换到IO线程执行网络请求
            val res = withContext(Dispatchers.IO) {
                Log.d("CoroutinesActivity", "网络请求 [线程: ${Thread.currentThread().name}]")
                delay(2000)
                "请求成功, 7666777"
            }

            // 1.2 自动切换回UI(main)线程
            Log.d("CoroutinesActivity", "更新UI [线程: ${Thread.currentThread().name}] - $res")
        }

        Log.d("CoroutinesActivity", "222222222 [线程: ${Thread.currentThread().name}]")


    }
}